package com.market.cash.ui.fragment

import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.market.cash.R
import com.market.cash.databinding.CashRepayBinding
import com.market.cash.pro.ProFragment
import com.market.cash.ui.activity.KefuActivity
import com.market.cash.ui.activity.PinStatusActivity
import com.market.cash.ui.adapter.CashRootRepayAdapter
import com.market.cash.ui.presenter.CashRootRepayPresenter
import com.market.cash.ui.view.ICashRootRepayView
import com.market.cash.utils.event.CashRootEventData
import com.market.cash.utils.event.CashRootEventType
import com.market.cash.utils.helper.CashRootCustomConfigsHelper
import org.json.JSONObject

/**
 * CashRoot
 * @Author wwdeng
 * @CreateTime: 2024/10/18 16:52
 * @Annotation：待还款
 */
class RepayFragment: ProFragment(),ICashRootRepayView {
    lateinit var binding: CashRepayBinding
    private var presenter: CashRootRepayPresenter? = null
    //订单列表
    private var orderAdapter: CashRootRepayAdapter? = null

    override fun getCashRootRootView(inflater: LayoutInflater): View {
        binding = CashRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initCashRootView() {
        setCashRootTitleBarVisibility(View.VISIBLE)
        setCashRootTitleBarColor(Color.parseColor("#FFFFFF"))
        setCashRootBackBtnVisibility(View.INVISIBLE)
        setCashRootRightBtnRes(R.mipmap.cash_kefu_black)
        setCashRootTextTitle(getString(R.string.repay_title))
        initCashRootRefreshLayout()
        initCashRootRecyclerView()

    }

    override fun initCashRootListener() {
        rootViewBinding.imgKefu.setOnClickListener {
            KefuActivity.start(requireContext(),"Repay Page")
            addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_CUSTOMER,"Repay Page")
        }
    }

    override fun initCashRootData() {
        presenter = CashRootRepayPresenter(this)
        presenter!!.loadCashRootOrderListAction()

        //牌照信息
        if (!CashRootCustomConfigsHelper.isCashRootShowLicense()){
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.removeAllViews()
            binding.licenseLayout.addView(initCashRootLicenseView())
            binding.licenseLayout.visibility = View.VISIBLE
        }
    }

    /* 初始化刷新 */
    private fun initCashRootRefreshLayout() {
        //禁止加载
        binding.refreshLayout.setEnableLoadMore(false)
        binding.refreshLayout.setEnableAutoLoadMore(false)
        binding.refreshLayout.setOnRefreshListener {
            //刷新产品列表
            getAct().publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESH))
        }
        binding.refreshLayout.setOnLoadMoreListener {
            binding.refreshLayout.finishLoadMore()
        }
    }

    /**
     * 产品列表
     */
    private fun initCashRootRecyclerView(){
//        binding.recyclerView.setHasFixedSize(true)
//        binding.recyclerView.isNestedScrollingEnabled = false
//        binding.recyclerView.isFocusableInTouchMode = false //不需要焦点
        val layoutManager = LinearLayoutManager(context)
        binding.recyclerView.layoutManager = layoutManager
        orderAdapter = CashRootRepayAdapter(binding.recyclerView)
        orderAdapter!!.setOnItemChildClickListener { _, childView, position ->
            val item = this.orderAdapter!!.getItem(position)
            item.put("index",position)
            presenter!!.setCashRootSelectOrder(item)
            when(childView.id){
                R.id.btnRepay -> {//还款
                    presenter!!.loadCashRootPayLinkAction()
                    addCashRootEventPoint(CashRootEventType.CLICK.CASHROOT_CLICK_LOAN_REPAY,"${item.optString("product")} Repay")
                }
                R.id.imgCheck -> {//展开、收起
                    presenter!!.checkCashRootOpenOrClose()
                }
                R.id.textRepayEmpty -> {//去申请
                    publishEventData(CashRootEventData(CashRootEventData.TYPE.CASHROOT_SHOW_HOME))
                }
            }
        }
        binding.recyclerView.adapter = orderAdapter
    }

    /**
     * 设置订单列表
     */
    override fun showCashRootOrderList(orderList: ArrayList<JSONObject>) {
        orderAdapter!!.data = orderList
    }

    /**
     * 刷新指定item
     */
    override fun notifyCashRootItem(position: Int) {
        orderAdapter!!.notifyItemChanged(position,"checkShowDetails")
    }

    /**
     * 跳转还款链接
     */
    override fun showCashRootPayLink(linkUrl: String) {
        val uri = Uri.parse(linkUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * PIN流程，进入订单状态查询
     */
    override fun showCashRootPaymentStatusPage(pName: String, pToken: String, thirdOrderId: String) {
        PinStatusActivity.start(requireContext(),pName,pToken,thirdOrderId)
    }

    override fun onCashRootEvent(event: CashRootEventData) {
        super.onCashRootEvent(event)
        when(event.eventType){
            CashRootEventData.TYPE.CASHROOT_PRODUCT_REFRESHED -> {//刷新产品列表完成
                presenter!!.loadCashRootOrderListAction()
            }
            CashRootEventData.TYPE.CASHROOT_PRODUCT_FINISHED -> {
                hideCashRootLoading()
            }
            else -> {

            }
        }
    }

    override fun hideCashRootLoading() {
        super.hideCashRootLoading()
        binding.refreshLayout.finishRefresh()
    }

    override fun onStart() {
        super.onStart()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_REPAY_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        addCashRootEventPoint(CashRootEventType.PAGE.CASHROOT_PAGE_LOAN_REPAY_END)
    }
}